document.addEventListener('DOMContentLoaded', () => {
    const quadrants = {
        list1: '重要且紧急',
        list2: '重要不紧急',
        list3: '紧急不重要',
        list4: '不紧急不重要'
    };

    let showCompletedTasks = true; // 默认显示已完成任务

    // 获取 DOM 元素
    const addTaskButton = document.getElementById('add-task-button');
    const toggleCompletedButton = document.getElementById('toggle-completed-tasks');
    const taskModal = document.getElementById('task-modal');
    const closeModal = document.querySelector('#task-modal .close');
    const taskForm = document.getElementById('task-form');

    // 打开添加任务模态框
    addTaskButton.addEventListener('click', () => {
        taskModal.style.display = 'block';
    });

    // 关闭添加任务模态框
    closeModal.addEventListener('click', () => {
        taskModal.style.display = 'none';
    });

    // 切换显示/隐藏已完成任务
    toggleCompletedButton.addEventListener('click', () => {
        showCompletedTasks = !showCompletedTasks; // 切换状态
        toggleCompletedButton.textContent = showCompletedTasks ? '隐藏已完成任务' : '显示已完成任务';
        fetchTasks(); // 刷新任务列表
    });

    // 表单提交（添加任务）
    taskForm.addEventListener('submit', async (e) => {
        e.preventDefault();
        const taskName = document.getElementById('task-name').value;
        const dueDate = document.getElementById('due-date').value;
        const taskTag = document.getElementById('task-tag').value;
        const taskQuadrant = document.getElementById('task-quadrant').value;

        // 发送 POST 请求添加任务
        const response = await fetch('/tasks', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ name: taskName, dueDate, tag: taskTag, quadrant: taskQuadrant })
        });

        if (response.ok) {
            taskModal.style.display = 'none';
            fetchTasks(); // 刷新任务列表
        }
    });

    // 获取任务数据
    async function fetchTasks() {
        const response = await fetch('/tasks');
        const tasks = await response.json();
        renderTasks(tasks);
    }

    // 渲染任务
    function renderTasks(tasks) {
        for (const listId in quadrants) {
            const listElement = document.getElementById(listId);
            listElement.innerHTML = '';
            const quadrantTasks = tasks.filter(task => task.quadrant === quadrants[listId]);

            quadrantTasks.forEach(task => {
                if (showCompletedTasks || !task.completed) {
                    const taskElement = createTaskElement(task);
                    listElement.appendChild(taskElement);
                }
            });
        }
    }

    // 创建任务元素
    function createTaskElement(task) {
        const li = document.createElement('li');
        li.draggable = true;
        li.dataset.id = task.id;
        if (task.completed) li.classList.add('completed');

        const taskInfo = document.createElement('span');
        taskInfo.textContent = `${task.name} - ${task.dueDate} [${task.tag}]`;
        li.appendChild(taskInfo);

        const actions = document.createElement('div');
        actions.className = 'actions';

        // 完成按钮
        const completeButton = document.createElement('button');
        completeButton.textContent = '完成';
        completeButton.onclick = async () => {
            await fetch(`/tasks/${task.id}/complete`, { method: 'PUT' });
            li.classList.toggle('completed');
            fetchTasks(); // 刷新任务列表
        };

        // 编辑按钮
        const editButton = document.createElement('button');
        editButton.textContent = '编辑';
        editButton.onclick = () => openEditModal(task);

        // 删除按钮
        const deleteButton = document.createElement('button');
        deleteButton.textContent = '删除';
        deleteButton.onclick = async () => {
            await fetch(`/tasks/${task.id}`, { method: 'DELETE' });
            li.remove();
        };

        actions.appendChild(completeButton);
        actions.appendChild(editButton);
        actions.appendChild(deleteButton);
        li.appendChild(actions);

        // 拖动功能
        li.addEventListener('dragstart', handleDragStart);
        li.addEventListener('dragend', handleDragEnd);

        return li;
    }

    // 打开编辑模态框
    function openEditModal(task) {
        const editModal = document.getElementById('edit-modal');
        const editForm = document.getElementById('edit-task-form');

        // 填充当前任务数据
        document.getElementById('edit-task-name').value = task.name;
        document.getElementById('edit-due-date').value = task.dueDate;
        document.getElementById('edit-task-tag').value = task.tag;
        document.getElementById('edit-task-quadrant').value = task.quadrant;

        // 显示模态框
        editModal.style.display = 'block';

        // 表单提交（编辑任务）
        editForm.onsubmit = async (e) => {
            e.preventDefault();
            const updatedTask = {
                name: document.getElementById('edit-task-name').value,
                dueDate: document.getElementById('edit-due-date').value,
                tag: document.getElementById('edit-task-tag').value,
                quadrant: document.getElementById('edit-task-quadrant').value
            };

            // 发送 PUT 请求更新任务
            const response = await fetch(`/tasks/${task.id}`, {
                method: 'PUT',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(updatedTask)
            });

            if (response.ok) {
                editModal.style.display = 'none';
                fetchTasks(); // 刷新任务列表
            }
        };

        // 关闭模态框
        const closeEditModal = document.querySelector('#edit-modal .close');
        closeEditModal.onclick = () => {
            editModal.style.display = 'none';
        };
    }

    // 拖动开始
    function handleDragStart(e) {
        e.dataTransfer.setData('text/plain', e.target.dataset.id);
        e.target.style.opacity = '0.4'; // 拖动时降低透明度
    }

    // 拖动结束
    function handleDragEnd(e) {
        e.target.style.opacity = '1'; // 拖动结束后恢复透明度
    }

    // 拖动放置
    document.querySelectorAll('.task-list').forEach(list => {
        list.addEventListener('dragover', e => {
            e.preventDefault(); // 允许放置
            e.dataTransfer.dropEffect = 'move';
            const afterElement = getDragAfterElement(list, e.clientY);
            const draggable = document.querySelector('.dragging');
            if (afterElement == null) {
                list.appendChild(draggable);
            } else {
                list.insertBefore(draggable, afterElement);
            }
        });

        list.addEventListener('drop', async e => {
            e.preventDefault();
            const taskId = e.dataTransfer.getData('text/plain');
            const newQuadrant = e.target.closest('.quadrant').querySelector('h2').textContent;

            // 更新任务的象限
            const response = await fetch(`/tasks/${taskId}/quadrant`, {
                method: 'PUT',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ quadrant: newQuadrant })
            });

            if (response.ok) {
                fetchTasks(); // 刷新任务列表
            }
        });
    });

    // 获取拖动后的元素位置
    function getDragAfterElement(container, y) {
        const draggableElements = [...container.querySelectorAll('li:not(.dragging)')];

        return draggableElements.reduce((closest, child) => {
            const box = child.getBoundingClientRect();
            const offset = y - box.top - box.height / 2;
            if (offset < 0 && offset > closest.offset) {
                return { offset: offset, element: child };
            } else {
                return closest;
            }
        }, { offset: Number.NEGATIVE_INFINITY }).element;
    }

    // 初始化
    fetchTasks();
});